import WPT from 'wpt';
import getMd5 from './getMd5';
import getExif from './getExif';

function getBase64(localId) {
    // 需要注意的是微信返回的localId并不是原始图片的base64结果，而是压缩后的图片的base64
    return new Promise((res, rej) => {
        // 在某些极端环境下安卓似乎无法频繁获取localId，因此这里做了一个延时处理
        setTimeout(() => {
            rej(new Error('getLocalImgDataFail wx no response'));
        }, 2000);
        window.wx.getLocalImgData({
            localId, // 图片的localID
            success(LocalRes) {
                res(LocalRes.localData);
            },
            fail() {
                rej(new Error('getLocalImgDataFail wx get localImage fail'));
            },
        });
    });
}

function getWXTmpFile(id) {
    return new Promise(res => {
        const xml = new XMLHttpRequest();
        const apiError = WPT.Util.handleApi('/cors/wx-image', { useGoApi: true });
        // xml.open('GET', `//api.weipaitang.com/wechat/v1.0/im/wx-image?mediaId=${id}`, true);
        xml.open('GET', `${apiError}?mediaId=${id}`, true);
        xml.responseType = 'blob';
        xml.onreadystatechange = () => {
            if (xml.readyState == 4) {
                res(xml.response);
            }
        };
        xml.send();
    });
}

const getNaturalWH = (blob, width, height) => new Promise(resolve => {
    const img = new Image();
    img.onload = () => {
        resolve([img.naturalWidth, img.naturalHeight]);
    };
    img.onerror = () => {
        resolve([width, height]);
    };
    try {
        img.src = URL.createObjectURL(blob);
    } catch (e) {
        resolve([width, height]);
    }
});

export default function wxUploadImg(callback, imgLimit, isCut, openRemote, files, addMD5, getFile) {
    let localIds = [];
    let imageNum = 0;
    const serverIds = [];
    let date = new Date();
    if (WPT && WPT.nowTime) {
        date = new Date(WPT.nowTime * 1000);
    }
    const month = date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : date.getMonth() + 1;
    const strDate = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate().toString();
    const strTime = date.getFullYear().toString() + month + strDate;
    const fileInfos = [];

    // 上传图片
    function upload() {
        if (localIds && localIds[imageNum]) {
            const wxCurrentLoadId = localIds[imageNum];
            const _img = document.createElement('img');
            const apiError = WPT.Util.handleApi('/cors/wx-image', { useGoApi: true });
            const load = type => {
                window.wx.uploadImage({
                    localId: localIds[imageNum],
                    isShowProgressTips: 0,
                    success(res) {
                        const uploadHandel = async () => {
                            let _serverId = strTime + res.serverId;
                            let fileBase64 = '';

                            // 拼接serverId
                            let { width, height } = _img;
                            if (_img.width > 0 && _img.height > 0) {
                                try {
                                    const wxFile = await getWXTmpFile(res.serverId);
                                    const exif = await getExif(wxFile);
                                    const { isRotate, ImageWidth, ImageHeight } = exif;

                                    if (ImageWidth && ImageHeight) {
                                        [width, height] = isRotate
                                            ? [ImageHeight, ImageWidth]
                                            : [ImageWidth, ImageHeight];
                                    } else {
                                        [width, height] = await getNaturalWH(wxFile, width, height);
                                    }
                                } catch (err) {
                                    WPT.report({
                                        type: 'wxUploadImgGetExifFail',
                                        err,
                                    });
                                }

                                _serverId += `-W${width}H${height}`;

                                try {
                                    fileBase64 = await getBase64(wxCurrentLoadId);
                                } catch (err) {
                                    console.log(err);
                                }

                                // 添加md5
                                if (addMD5 && fileBase64) {
                                    try {
                                        const md5Str = await getMd5(fileBase64);
                                        // 添加md5
                                        if (md5Str) {
                                            _serverId += `|md5-${md5Str}`;
                                        }
                                    } catch (err) {
                                        WPT.reportError({
                                            type: 'uploadImg-md5-fail',
                                            process: `${imageNum}/${localIds.length}`,
                                            err: err.message,
                                        });
                                    }
                                }
                            }

                            if (res.serverId && _img.width > 0 && _img.height > 0) {
                                // 一切正常 就push
                                serverIds.push(_serverId);
                                fileInfos.push({
                                    name: _serverId,
                                    file: fileBase64,
                                });
                            } else {
                                localIds[imageNum] = ''; // 如果出现图片异常的，本地图片设为空，serverIds不push （微信有时候会返回undefind或者获得不到宽高）
                            }
                            imageNum += 1;
                            WPT.Modal.loading(`正在上传 ${imageNum} / ${localIds.length}`, { mask: true });
                            if (imageNum < localIds.length) {
                                setTimeout(upload, 300);
                            } else {
                                setTimeout(() => {
                                    WPT.Modal.loading.close();
                                    let handelLocalIds = localIds;
                                    if (localIds.length != serverIds.length) {
                                        // 处理下数组里为空的图片
                                        handelLocalIds = [];
                                        for (let num = 0; num < localIds.length; num++) {
                                            if (localIds[num]) {
                                                handelLocalIds.push(localIds[num]);
                                            }
                                        }
                                    }

                                    if (callback) {
                                        if (getFile) {
                                            callback(serverIds, handelLocalIds, fileInfos);
                                        } else {
                                            callback(serverIds, handelLocalIds);
                                        }
                                    }
                                }, 300);
                            }
                        };
                        if (type == 'onerror') {
                            window.wx.getLocalImgData({
                                localId: localIds[imageNum], // 图片的localID
                                success(LocalRes) {
                                    if (openRemote) {
                                        localIds[imageNum] = `${
                                            apiError.indexOf('http') == -1 ? 'https:' : ''
                                        }${apiError}?mediaId=${res.serverId}`;
                                    } else {
                                        localIds[imageNum] = LocalRes.localData;
                                    }
                                    _img.src = localIds[imageNum];
                                    _img.onerror = uploadHandel;
                                    _img.onload = uploadHandel;
                                },
                            });
                        } else {
                            uploadHandel();
                        }
                    },
                    fail(res) {
                        WPT.reportError({
                            type: 'wx-uploadImgFail',
                            err: JSON.stringify(res),
                        });
                        WPT.Modal.loading(`上传失败${JSON.stringify(res)}`, { time: 2000 });
                    },
                });
            };
            _img.onload = () => load('onload');
            _img.onerror = () => load('onerror');
            _img.src = localIds[imageNum];
        }
    }

    window.wx.chooseImage({
        count: imgLimit || 9,
        success(res) {
            WPT.Modal.loading('正在上传...', { mask: true });
            localIds = res.localIds; // ["wxLocalRe*://5645646454"]
            setTimeout(upload, 200);
        },
    });
}
